//https://api.douban.com/v2/book/isbn/:name
const https = require("https");
const { mysql } = require("../qcloud");

module.exports = async (ctx) => {
  const { isbn, openId } = ctx.request.body;
  if (isbn && openId) {
     const findRes=await mysql('books').select().where('isbn',isbn)
     if(findRes.length){
       ctx.state = {
         code: -1,
         data: {
           msg: "图书已存在"
         }
       };
       return
     }

    let url = "https://api.douban.com/v2/book/isbn/:" + isbn;
    const bookinfo = await getJson(url);
    // console.log(bookinfo);
    const rate = bookinfo.rating.average;
    /* const title = bookinfo.title;
     const image=bookinfo.image
     const alt = bookinfo.alt;
     const publisher = bookinfo.publisher;
     const summary = bookinfo.summary;
     const price = bookinfo.price;*/
    const { title, image, alt, publisher, summary, price } = bookinfo;
    const tags = bookinfo.tags.map(v => {
      return `${v.title}${v.count}`;
    }).join(",");
    const author = bookinfo.author.join(",");
    // console.log({rate,title,image,alt,publisher,summary,price,tags,author})
    try {
      await mysql("books").insert({ isbn, openId, rate, title, image, alt, publisher, summary, price, tags, author });
      ctx.state.data = {
        title,
        msg: "success"
      };
    } catch (e) {
      ctx.state = {
        code: -1,
        data: {
          msg: "添加失败：" + e.sqlMessage
        }
      };
    }
  }
};

function getJson(url) {
  return new Promise((resolve, reject) => {
    https.get(url, res => {
      let urlData = "";
      res.on("data", data => {
        urlData += data;
      });
      res.on("end", data => {
        const bookinfo = JSON.parse(urlData);
        //如果存在标题
        if (bookinfo.title) {
          resolve(bookinfo);
        }
        reject(bookinfo);
        /*
                urlData += data;
        */
      });
    });
  });
}
